package com.ympc.controller;

import com.ympc.pojo.Student;
import com.ympc.pojo.Users;
import com.ympc.service.StudentService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 学生管理控制器
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    
    @Resource
    private StudentService studentService;
    
    /**
     * 学生主页
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String studentHome(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        // 确保session中有student对象
        Student student = (Student) session.getAttribute("student");
        if (student == null) {
            student = studentService.getStudentByUserId(user.getId());
            if (student == null) {
                // 如果还没有学生信息，创建一个空的学生对象
                student = new Student();
                student.setUserId(user.getId());
            }
            session.setAttribute("student", student);
        }
        
        model.addAttribute("student", student);
        return "student";
    }
    
    /**
     * 我的课程页面
     */
    @RequestMapping(value = "/courses", method = RequestMethod.GET)
    public String myCourses(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Student student = studentService.getStudentByUserId(user.getId());
        List<com.ympc.pojo.CourseVO> courses = studentService.getCoursesByStudentUserId(user.getId());
        model.addAttribute("courses", courses);
        model.addAttribute("student", student);
        session.setAttribute("student", student);
        return "student/courses";
    }
    
    /**
     * 学生列表页面
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String studentList(Model model, @RequestParam(required = false) String className) {
        List<Student> students;
        if (className != null && !className.isEmpty()) {
            students = studentService.getStudentsByClass(className);
        } else {
            students = studentService.getAllStudents();
        }
        model.addAttribute("students", students);
        model.addAttribute("className", className);
        return "student/list";
    }
    
    /**
     * 添加学生页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addStudentPage() {
        return "student/add";
    }
    
    /**
     * 添加学生
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addStudent(Student student, Model model) {
        try {
            // 验证必填字段
            if (student.getStudentNumber() == null || student.getStudentNumber().trim().isEmpty()) {
                model.addAttribute("error", "学号不能为空");
                return "student/add";
            }
            if (student.getName() == null || student.getName().trim().isEmpty()) {
                model.addAttribute("error", "姓名不能为空");
                return "student/add";
            }
            
            boolean success = studentService.addStudent(student);
            if (success) {
                model.addAttribute("message", "学生添加成功！登录账号已自动创建：用户名=" + student.getStudentNumber() + "，密码=123456");
                return "redirect:/student/list";
            } else {
                model.addAttribute("error", "学生添加失败，可能是学号已存在或用户名已存在");
                return "student/add";
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "添加学生时出错：" + e.getMessage());
            return "student/add";
        }
    }
    
    /**
     * 编辑学生页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editStudentPage(@RequestParam Integer id, Model model) {
        Student student = studentService.getStudentById(id);
        if (student == null) {
            model.addAttribute("error", "学生不存在");
            return "redirect:/student/list";
        }
        model.addAttribute("student", student);
        return "student/edit";
    }
    
    /**
     * 更新学生信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateStudent(Student student, Model model) {
        boolean success = studentService.updateStudent(student);
        if (success) {
            model.addAttribute("message", "学生信息更新成功");
            return "redirect:/student/list";
        } else {
            model.addAttribute("error", "学生信息更新失败");
            model.addAttribute("student", student);
            return "student/edit";
        }
    }
    
    /**
     * 删除学生
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deleteStudent(@RequestParam Integer id, Model model) {
        boolean success = studentService.deleteStudent(id);
        if (success) {
            model.addAttribute("message", "学生删除成功");
        } else {
            model.addAttribute("error", "学生删除失败");
        }
        return "redirect:/student/list";
    }
    
    /**
     * 设置页面
     */
    @RequestMapping(value = "/settings", method = RequestMethod.GET)
    public String settingsPage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Student student = studentService.getStudentByUserId(user.getId());
        model.addAttribute("student", student);
        // 将学生信息添加到session，以便在所有页面使用
        session.setAttribute("student", student);
        return "student/settings";
    }
    
    /**
     * 上传头像
     */
    @RequestMapping(value = "/avatar/upload", method = RequestMethod.POST)
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file,
                              HttpSession session,
                              Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Student student = studentService.getStudentByUserId(user.getId());
        if (student == null) {
            model.addAttribute("error", "学生信息不存在");
            return "student/settings";
        }
        
        if (file == null || file.isEmpty()) {
            model.addAttribute("error", "请选择要上传的头像文件");
            model.addAttribute("student", student);
            return "student/settings";
        }
        
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                model.addAttribute("error", "只能上传图片文件");
                model.addAttribute("student", student);
                return "student/settings";
            }
            
            // 创建上传目录
            String uploadDir = "uploads/avatars/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成文件名：学生ID_时间戳.扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "student_" + student.getId() + "_" + System.currentTimeMillis() + extension;
            String filePath = uploadDir + fileName;
            Path destPath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), destPath);
            
            // 删除旧头像（如果存在）
            if (student.getAvatar() != null && !student.getAvatar().isEmpty()) {
                try {
                    Path oldAvatarPath = Paths.get(student.getAvatar());
                    if (Files.exists(oldAvatarPath)) {
                        Files.delete(oldAvatarPath);
                    }
                } catch (Exception e) {
                    // 忽略删除旧文件时的错误
                    e.printStackTrace();
                }
            }
            
            // 更新学生头像路径
            student.setAvatar(filePath);
            boolean success = studentService.updateStudent(student);
            
            if (success) {
                model.addAttribute("message", "头像上传成功");
                // 重新查询学生信息
                student = studentService.getStudentByUserId(user.getId());
                // 更新session中的学生信息
                session.setAttribute("student", student);
            } else {
                model.addAttribute("error", "头像上传失败");
            }
            
            model.addAttribute("student", student);
            return "student/settings";
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("error", "头像上传时出错：" + e.getMessage());
            model.addAttribute("student", student);
            return "student/settings";
        }
    }
    
    /**
     * 修改密码页面
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.GET)
    public String changePasswordPage() {
        return "student/changePassword";
    }
    
    /**
     * 修改密码
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public String changePassword(@RequestParam String oldPassword, 
                                 @RequestParam String newPassword,
                                 @RequestParam String confirmPassword,
                                 HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        // 验证新密码长度
        if (newPassword.length() < 6) {
            model.addAttribute("error", "密码长度至少6位");
            return "student/changePassword";
        }
        
        // 验证新密码和确认密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("error", "新密码和确认密码不一致");
            return "student/changePassword";
        }
        
        boolean success = studentService.changePassword(user.getId(), oldPassword, newPassword);
        if (success) {
            model.addAttribute("message", "密码修改成功");
        } else {
            model.addAttribute("error", "旧密码错误或修改失败");
        }
        return "student/changePassword";
    }
}

